package reesoft.common.util;

/**
 * 公用字符串处理单元
 *
 * Created by reesoft on 2017-07-14
 */
public class StringUtil extends org.apache.commons.lang3.StringUtils
{
    public static boolean isBlank(final String string)
    {
        return string == null || string.trim().isEmpty();
    }

    public static boolean isEmpty(final String string)
    {
        return string == null || string.isEmpty();
    }

    /**
     * 从一个大字符串中截取符合指定特征的子字符串
     *
     * @param content 原字符串
     * @param before  子字符串前面的特征子字符串，空字符串表示从头开始
     * @param after   子字符串后面的特征子字符串，空字符串表示到字符串尾
     * @return 匹配的子字符串，无匹配则返回空字符串
     */
    public static String getSubString(final String content, final String before, final String after)
    {
        int beforePosition = 0;

        if (!isEmpty(before))
        {
            beforePosition = content.indexOf(before);

            if (beforePosition < 0)
            {
                return "";
            }

            beforePosition += before.length();
        }

        int afterPosition = content.length();

        if (!isEmpty(after))
        {
            afterPosition = content.indexOf(after, beforePosition);
        }

        if (0 <= beforePosition && beforePosition < afterPosition)
        {
            return content.substring(beforePosition, afterPosition);
        }

        return "";
    }

    /**
     * 生成指定长度的纯 0 字符串
     *
     * @param length 字符串长度
     * @return 纯 0 字符串
     */
    public static String generateZeroString(final int length)
    {
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < length; i++)
        {
            stringBuilder.append('0');
        }

        return stringBuilder.toString();
    }

    /**
     * 把数字转换为定长的字符串，长度不够前面补 0
     *
     * @param number      数字
     * @param fixedLength 字符串长度
     * @return 定长的字符串
     */
    public static String toFixedLengthString(final long number, final int fixedLength)
    {
        StringBuilder stringBuilder = new StringBuilder();
        String tail = String.valueOf(number);

        if (fixedLength - tail.length() > 0)
        {
            stringBuilder.append(generateZeroString(fixedLength - tail.length()));
        }

        stringBuilder.append(tail);

        return stringBuilder.toString();
    }
}
